package org.icf.rest.service.security;

import java.io.IOException;
import java.io.Writer;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

/**
 * 
 */
public class JsonAuthenticationFailureHandler  implements AuthenticationFailureHandler {
    
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException ae) throws IOException, ServletException {

        HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(response);

        Writer out = responseWrapper.getWriter();
        responseWrapper.setContentType("application/json");
        
        out.write("{ \"success\": false, \"errors\": { \"reason\": \"Login failed. " + ae.getMessage() + "\" }}");
        out.close();
    }
}
